package cn.loioi.web.controller.admin.user;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.loioi.multi.mysql.model.SysRole;
import cn.loioi.multi.service.user.SysResourceService;
import cn.loioi.multi.service.user.SysRoleService;
import cn.loioi.web.common.BaseJqGridController;

/**
 * <br>
 * (c) Copyright 2016 by <br>
 * @description :角色管理 <br>
 * @file_name :RoleContorller.java <br>
 * @system_name :multi_project_web <br>
 * @author :yyzh <br>
 * @创建时间 :2016年7月26日 下午1:43:39
 */
@Controller
@RequestMapping("/admin/user/role")
public class RoleContorller extends BaseJqGridController<SysRole, SysRoleService> {
	private @Resource SysResourceService resourceService;

	@Autowired
	public RoleContorller(SysRoleService service) {
		super("admin/user/role/", "user:role", service);
	}

	@Override
	@RequiresRoles("manage")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.index(request, response, model);
	}

	/**
	 * 权限列表
	 * @param model
	 * @param id
	 * @return
	 */
	@RequiresRoles("manage")
	@RequestMapping("permission/list.json")
	public Model permissionList(Model model, @RequestParam(name = "id", required = true, defaultValue = "") Integer id) {
		List<Map<String, Object>> list = resourceService.selectRoleResource(id);
		if (list != null) {
			return renderSuccess(list, model);
		} else {
			return renderFail(model, "数据为空");
		}
	}

	/**
	 * 更新权限
	 * @param json
	 * @param model
	 * @return
	 */
	@RequiresRoles("manage")
	@RequestMapping("permission/save.json")
	public Model permissionSave(@RequestBody JSONObject json, Model model) {
		if (json == null) return renderFail(model, "参数为空");
		Integer role = json.getInteger("role");
		JSONArray ids = json.getJSONArray("ids");
		return renderSuccess(resourceService.insertRoleResource(role, ids), model);
	}
}
